import axios, {AxiosRequestConfig} from 'axios';
import {InterfaceResponse} from '@/interface/InterfaceResponse';

// axios.interceptors.request.use((config: AxiosRequestConfig) => {
//     if (config.method === 'post') {
//         const qs = require('qs');
//         config.data = qs.stringify(config.data);
//     }
//     return config;
// });


export default class Http {
    public static async post(url: string, obj: any = {}): Promise<InterfaceResponse> {
        console.log(obj)
        const qs = require('qs');
        const promise = new Promise<PromiseLike<any>>((resolve, reject) => {
            axios.post(`${url}?_self=${Date.parse(new Date().toString())}`, qs.stringify(obj), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then((res: any) => {
                resolve(res.data);
            }).catch((error: any) => {
                reject(error);
            });
        });
        return promise;
    }

    public static async get(url: string, obj: any = {}): Promise<InterfaceResponse> {
        obj._self = Date.parse(new Date().toString());
        let parameter: string = Object.keys(obj).length > 0 ? '?' : '';
        parameter = parameter + Object.keys(obj)
            .map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`)
            .join('&');
        const promise = new Promise<PromiseLike<any>>((resolve, reject) => {
            axios.get(`${url}${(parameter)}`).then((res: any) => {
                resolve(res.data);
            }).catch((error: any) => {
                reject(error);
            });
        });
        return promise;
    }

    public static async upload(url: string, obj: any = {}): Promise<InterfaceResponse> {
        const formData = new FormData();
        for (const key of Object.keys(obj)) {
            formData.append(key, obj[key]);
        }
        const promise = new Promise<PromiseLike<any>>((resolve, reject) => {
            const instance = axios.create({withCredentials: true});
            instance.post(`${url}?_self=${Date.parse(new Date().toString())}`, formData, {
                onUploadProgress: (progressEvent: ProgressEvent) => {
                    const progressNum: number = (progressEvent.loaded / progressEvent.total) * 100;
                },
            }).then((res: any) => {
                resolve(res.data);
            }).catch((error: any) => {
                reject(error);
            });
        });
        return promise;
    }
}
